package com.bocai.grainshop.order.config;

import feign.RequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
public class GuliFeignConfig {

    /**
     * @Author: SunJinbo
     * @Description  给容器加一个feign远程调用的请求拦截器
     * @Param []
     * @return feign.RequestInterceptor
     * @Data Created in 2022/4/21 18:04
     */

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return requestTemplate -> {
            log.info("feign拦截器线程{}"+Thread.currentThread().getId());
            //获取当前请求进来的所有请求信息 底层也是Threadload实现
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if(attributes != null){
                HttpServletRequest request = attributes.getRequest();
                if(request != null){
                    //同步cookie
                    requestTemplate.header("Cookie",request.getHeader("Cookie"));
                }
            }
        };
    }
}
